package com.xxxx.server.controller;

import com.xxxx.server.entity.CompletionStatus;
import com.xxxx.server.entity.Course;
import com.xxxx.server.entity.StudentTranscript;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.RespPageBean;
import com.xxxx.server.service.CourseService;
import com.xxxx.server.service.impl.AdminServiceImpl;
import com.xxxx.server.service.impl.CourseServiceImpl;
import com.xxxx.server.utils.AdminUtils;
import com.xxxx.server.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @description: 课程模块
 * @author: Honors
 * @create: 2021-11-13
 */
@RestController
@RequestMapping("/course")
@Api(value = "课程管理", tags = "课程管理")
public class CourseController {

    @Resource
    private CourseService courseService;

    @Resource
    private CourseServiceImpl courseServiceImpl;

    @Resource
    private AdminServiceImpl adminService;

    @ApiOperation(value = "课程管理 - 添加课程")
    @PostMapping("/add")
    public RespBean add(@RequestBody Course course) {

        Course isExist = courseServiceImpl.getByTitle(course.getItm_title());
        if (null != isExist) {
            return RespBean.error("该课程名称已存在！");
        }
        // 编码
        course.setItm_uuid(FileUtils.getUUID(15));
        // 创建人
        course.setItm_user_id(AdminUtils.getCurrentAdmin().getId());
        // 设置结束状态默认未 未结束
        course.setItm_reserve_1("1");
        // 创建时间
        course.setItm_create_time(new Date());
        if (courseService.save(course)) {
            return RespBean.success("添加成功！");
        }
        return RespBean.success("操作失败！");
    }


    @ApiOperation(value = "课程管理 - 修改课程")
    @PostMapping("/update")
    public RespBean update(@RequestBody Course course) {
        // 结束课程
        if (!StringUtils.isEmpty(course.getItm_reserve_1())) {
            if (course.getItm_reserve_1().equals("0")) {
                // 是否有作业
                Integer exist = courseServiceImpl.getIsRegistered(course.getItm_id());
                if (exist == 0) {
                    return RespBean.success("该课程还未布置过作业，无法结束！");
                }
                // 无报名记录
                Integer stuExist = courseServiceImpl.getIsStudent(course.getItm_id());
                if (stuExist == 0) {
                    return RespBean.error("该课程还未有学生报名，无法结束！");
                }
                // 无提交记录
                Integer stuSubmitTK = courseServiceImpl.getIsStuSubmitTK(course.getItm_id());
                if (stuSubmitTK == 0) {
                    return RespBean.error("该课程还未有学生提交过作业，无法结束！");
                }
                // 有未打分记录
                Integer withScoreNull = courseServiceImpl.getWithScoreNull(course.getItm_id());
                if (withScoreNull > 0) {
                    return RespBean.error("该课程还有未打分的作业，请全部打分之后在提交！");
                }
                List<Integer> userIds = courseServiceImpl.getUserIdsByItmId(course.getItm_id());
                // 作业总数
                int tkCount = courseServiceImpl.getTKCountByItmId(course.getItm_id());
                // 课程结束时间
                Date date = new Date();
                for (Integer userId : userIds) {
                    Admin admin = adminService.getById(userId);
                    // 总分
                    double totalScore = 0.0;

                    // 各种分数
                    List<CompletionStatus> userVariousScores = courseServiceImpl.getUserVariousScores(course.getItm_id(), userId);
                    // 完成总数
                    int size = userVariousScores.size();
                    for (CompletionStatus userVariousScore : userVariousScores) {
                        // 作业得分
                        Double cs_fraction = userVariousScore.getCs_fraction();
                        // 总分
                        totalScore = totalScore + cs_fraction;

                    }
                    // 平均分
                    double average = totalScore / size;
                    StudentTranscript studentTranscript = new StudentTranscript();
                    studentTranscript.setStItmId(course.getItm_id());
                    studentTranscript.setStAverage(average);
                    studentTranscript.setStCompleteCount(size);
                    studentTranscript.setStTkCount(tkCount);
                    studentTranscript.setStTotalScore(totalScore);
                    studentTranscript.setStEndTime(date);
                    studentTranscript.setStUserId(admin.getId());
                    courseServiceImpl.addStudentTranscript(studentTranscript);
                }

                courseServiceImpl.updateCourseById(course);
                return RespBean.success("已结束课程！");
            }
        }
        Course isExist = courseServiceImpl.getCourseById(course.getItm_id());
        if (null != isExist && !StringUtils.isEmpty(course.getItm_title())) {
            if (!course.getItm_title().equals(isExist.getItm_title())) {
                Course byTitle = courseServiceImpl.getByTitle(course.getItm_title());
                if (null != byTitle) {
                    return RespBean.error("该课程名称已存在！");
                }
            }
        }
        if (courseServiceImpl.updateCourseById(course) > 0) {
            return RespBean.success("修改成功！");
        }
        return RespBean.success("操作失败！");
    }

    @ApiOperation(value = "课程管理 - 删除课程")
    @PostMapping("/delete")
    public RespBean update(@RequestParam Integer id) {
        // 课程已布置作业，学生已报名
        Integer exist = courseServiceImpl.getIsRegistered(id);
        if (exist > 0) {
            return RespBean.error("该课程已布置作业，无法删除！");
        }
        Integer stuExist = courseServiceImpl.getIsStudent(id);
        if (stuExist > 0) {
            return RespBean.error("该课程已有学生报名，无法删除！");
        }
        if (courseServiceImpl.deleteById(id) > 0) {
            return RespBean.success("删除成功！");
        }
        return RespBean.error("操作失败！");
    }

    @ApiOperation(value = "课程管理 - 批量删除课程")
    @PostMapping("/delete-ids")
    public RespBean update(@RequestBody List<Integer> ids) {
        // 课程已布置作业，学生已报名
        for (Integer id : ids) {
            Integer exist = courseServiceImpl.getIsRegistered(id);
            if (exist > 0) {
                return RespBean.error("所选数据中有已布置作业的课程，无法删除！");
            }
            Integer stuExist = courseServiceImpl.getIsStudent(id);
            if (stuExist > 0) {
                return RespBean.error("所选数据中有已报名的学生，无法删除！");
            }
        }
        for (Integer id : ids) {
            courseServiceImpl.deleteById(id);
        }
        return RespBean.success("删除成功！");
    }

    @ApiOperation("课程管理 - 批量报名")
    @PostMapping("/user-enroll")
    public RespBean fileUpload(@RequestBody MultipartFile file) throws IOException {
        return courseServiceImpl.batchImport(file);
    }

    @ApiOperation("课程管理 - 手动报名")
    @PostMapping("/manual-enroll")
    public RespBean manualEnroll(
            @RequestParam Integer itmId,
            @RequestParam String username) {
        if (courseServiceImpl.manualEnroll(itmId, username) > 0) {
            return RespBean.success("报名成功！");
        }
        return RespBean.error("该学生已经报名了该课程，操作失败！");
    }

    @ApiOperation("获取模板文件")
    @PostMapping("/getTemplate")
    public RespBean getTemplate(
            @ApiParam @RequestParam String path) {
        return courseServiceImpl.getTemplate(path);
    }

    @ApiOperation(value = "课程管理 - 课程分页")
    @GetMapping("/page")
    public RespPageBean getPage(
            @ApiParam @RequestParam(defaultValue = "1") Integer currentPage,
            @ApiParam @RequestParam(defaultValue = "10") Integer size,
            @ApiParam @RequestParam(required = false) String text,
            @ApiParam @RequestParam(required = false) Integer userId) {
        return courseServiceImpl.getPage(currentPage, size, text, userId);
    }

    @ApiOperation(value = "课程管理 - 添加作业")
    @PostMapping("/addCourseTask")
    public RespBean addCourseTask(
            @RequestParam Integer itmId,
            @RequestParam String name,
            @RequestParam String title) {
        courseServiceImpl.addCourseTask(itmId, name, title);
        return RespBean.success("添加成功！");
    }

    @ApiOperation(value = "课程管理 - 修改作业")
    @PostMapping("/updateCourseTask")
    public RespBean updateCourseTask(
            @RequestParam Integer tk_id,
            @RequestParam String name,
            @RequestParam String title) {
        courseServiceImpl.updateCourseTask(tk_id, name, title);
        return RespBean.success("修改成功！");
    }

    @ApiOperation(value = "课程管理 - 作业分页")
    @GetMapping("/courseTaskPage")
    public RespPageBean courseTaskPage(
            @ApiParam @RequestParam(defaultValue = "1") Integer currentPage,
            @ApiParam @RequestParam(defaultValue = "10") Integer size,
            @ApiParam @RequestParam(required = false) String text,
            @ApiParam @RequestParam Integer itmId) {
        return courseServiceImpl.courseTaskPage(currentPage, size, text, itmId);
    }

    @ApiOperation(value = "课程管理 - 提交作业")
    @PostMapping("/submitCourseTask")
    public RespBean submitCourseTask(@RequestBody CompletionStatus completionStatus) {
        return courseServiceImpl.submitCourseTask(completionStatus);
    }

    @ApiOperation(value = "课程管理 - 完成情况")
    @GetMapping("/submitTaskPage")
    public RespPageBean submitTaskPage(
            @ApiParam @RequestParam(defaultValue = "1") Integer currentPage,
            @ApiParam @RequestParam(defaultValue = "10") Integer size,
            @ApiParam @RequestParam(required = false) String text,
            @ApiParam @RequestParam Integer tkId) {
        return courseServiceImpl.submitTaskPage(currentPage, size, text, tkId);
    }

    @ApiOperation(value = "课程管理 - 作业打分")
    @PostMapping("/taskScore")
    public RespBean taskScore(
            @ApiParam @RequestParam Integer score,
            @ApiParam @RequestParam Integer csId) {
        courseServiceImpl.taskScore(score, csId);
        return RespBean.success("打分完成！");
    }

    @ApiOperation(value = "课程管理 - 学生成绩")
    @GetMapping("/studentTranscript")
    public RespPageBean studentTranscript(
            @ApiParam @RequestParam(defaultValue = "1") Integer currentPage,
            @ApiParam @RequestParam(defaultValue = "10") Integer size,
            @ApiParam @RequestParam(required = false) String text,
            @ApiParam @RequestParam(required = false) Integer userId,
            @ApiParam @RequestParam(required = false) Integer itmId) {
        return courseServiceImpl.getStudentTranscript(currentPage, size, text, userId, itmId);
    }

}
